<template>
  <div class="app-container">

    <Banner :title=bannerTitle @search="handleSearch" />

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单状态" style="width: 220px" prop="orderState">
        <el-select v-model="queryParams.orderState" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="Plus"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['orderManagement:docOrder:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Edit"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['orderManagement:docOrder:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="Delete"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['orderManagement:docOrder:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orderManagement:docOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="docOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="订单Id" align="center" prop="orderId" />-->
      <el-table-column label="签约团队" align="center" prop="teamName"/>
      <el-table-column label="订单金额" align="center" prop="orderPrice" />
      <el-table-column label="支付方式" align="center" prop="orderWay">
        <template #default="scope">
          <dict-tag :options="order_way" :value="scope.row.orderWay"/>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderState">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.orderState"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['orderManagement:docOrder:edit']">修改</el-button>-->
          <!-- 仅当订单状态为待支付时显示去支付按钮 -->
          <el-button
              v-if="scope.row.orderState === '0'"
              type="primary"
              link
              icon="Wallet"
              @click="handlePayment(scope.row.orderId)"
          >去支付</el-button>
          <el-button v-if="scope.row.orderState === '0'" link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['orderManagement:docOrder:remove']">取消订单</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改我的订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="docOrderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单金额" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="orderWay">
          <el-select v-model="form.orderWay" placeholder="请选择支付方式">
            <el-option
              v-for="dict in order_way"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderState">
          <el-select v-model="form.orderState" placeholder="请选择订单状态">
            <el-option
              v-for="dict in order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DocOrder">
import { listDocOrder, getDocOrder, delDocOrder, addDocOrder, updateDocOrder, payDocOrder } from "@/api/orderManagement/docOrder"
import {ElLoading, ElMessage} from "element-plus";
import Banner from "@/components/MyComponents/Banner.vue";

const { proxy } = getCurrentInstance()
const { order_status, order_way } = proxy.useDict('order_status', 'order_way')

const bannerTitle = ref('签约订单')

const docOrderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderState: null,
    // 添加搜索关键词字段
    searchKeyword: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

// 添加一个ref来存储原始数据
const originalDocOrderList = ref([])

/** 查询我的订单列表 */
function getList() {
  loading.value = true
  listDocOrder(queryParams.value).then(response => {
    docOrderList.value = response.rows
    originalDocOrderList.value = [...response.rows]  // 备份原始数据
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderPrice: null,
    orderWay: null,
    orderState: null
  }
  proxy.resetForm("docOrderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加我的订单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _orderId = row.orderId || ids.value
  getDocOrder(_orderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改我的订单"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["docOrderRef"].validate(valid => {
    if (valid) {
      if (form.value.orderId != null) {
        updateDocOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDocOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认取消该订单').then(function() {
    return delDocOrder(_orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orderManagement/docOrder/export', {
    ...queryParams.value
  }, `docOrder_${new Date().getTime()}.xlsx`)
}

/** 去支付按钮操作 */
function handlePayment(orderId) {
  //将订单id转成字符串类型，避免精度丢失
  const orderIdStr = orderId.toString();
  //显示加载状态
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: '正在跳转到支付页面...',
    spinner: 'el-icon-loading'
  });

  payDocOrder(orderIdStr).then(resp => {
    // 根据响应数据类型处理支付
    if (typeof resp === 'string' && resp.startsWith('<')) {
      // 如果返回的是HTML表单
      const divForm = document.getElementsByTagName("div");
      if (divForm.length) {
        document.body.removeChild(divForm[0]);
      }
      const div = document.createElement("div");
      div.innerHTML = resp; // data就是接口返回的form 表单字符串
      document.body.appendChild(div);
      // 检查表单是否存在再提交
      if (document.forms && document.forms.length > 0) {
        //document.forms[0].setAttribute("target", "_blank"); // 新开窗口跳转
        document.forms[0].submit();
      } else {
        console.error('支付表单未找到');
        ElMessage.error('支付表单未找到');
      }
    } else if (resp.code === 200) {
      // 如果返回的是JSON格式的成功响应
      ElMessage.success('支付成功');
      // 可以在这里添加支付成功后的处理逻辑
      // 例如刷新订单列表
      getList();
    } else {
      // 其他情况
      console.error('支付失败:', resp);
      ElMessage.error('支付失败: ' + (resp.msg || '未知错误'));
    }
  }).catch(error => {
    console.error('支付请求失败:', error);
    if (error.response) {
      // 服务器返回了错误响应
      console.error('错误响应数据:', error.response.data);
      console.error('错误状态码:', error.response.status);
      console.error('错误响应头:', error.response.headers);
      ElMessage.error(`订单: O_${orderIdStr}，支付失败：${error.response.data}`)
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('无响应的请求:', error.request);
      ElMessage.error(`订单: O_${orderIdStr}，支付失败：无响应`)
    } else {
      // 其他错误
      console.error('请求错误:', error.message);
      ElMessage.error(`订单: O_${orderIdStr}，支付失败：${error.message}`)
    }
  });
}

// 添加一个ref来存储搜索关键词
const searchKeyword = ref('')

// 添加一个计算属性来过滤数据
const filteredDocOrderList = computed(() => {
  if (!searchKeyword.value) {
    return docOrderList.value
  }
  return docOrderList.value.filter(item => 
    item.teamName && item.teamName.includes(searchKeyword.value)
  )
})

/** 处理Banner搜索 */
function handleSearch(query) {
  if (!query) {
    // 如果搜索关键词为空，恢复原始数据
    docOrderList.value = [...originalDocOrderList.value]
    total.value = originalDocOrderList.value.length
  } else {
    // 根据搜索关键词过滤数据
    docOrderList.value = originalDocOrderList.value.filter(item => 
      item.teamName && item.teamName.includes(query)
    )
    total.value = docOrderList.value.length
  }
  // 重置页码为第一页
  queryParams.value.pageNum = 1
}

getList()
</script>
